<template>
  <div class="Category-cantainer">
    <h2>文章分类</h2>
    <RightList :list="list" @select="handouClick" />
  </div>
</template>

<script>
import fetchData from "@/mixins/fatchData.js"; // 引入公共远程获取数据
import RightList from "./RightList.vue";
import { getBlogCategories } from "@/api/blog.js";
export default {
  mixins: [fetchData([])],
  computed: {
    // 1.获取所有分类的id
    categoryId() {
      return +this.$route.params.categoryId || -1;
    },
    list() {
      /**
       * articleCount :分类汇总
       * reduce()方法对数组中的每个元素执行一个由我们提供的函数(升序执行)，将其结果汇总为单个返回值
       *
       * totalArticleCount 获取分类汇总
       */
      const totalArticleCount = this.data.reduce(
        (a, b) => a + b.articleCount,
        0
      );
      const result = [
        { name: "全部", id: -1, articleCount: totalArticleCount },
        ...this.data,
      ];
      return result.map((it) => ({
        ...it,
        // 判断 当前id 是否等于 分类id 添加样式
        isSelect: it.id === this.categoryId,
        aside:`${it.articleCount}篇`
      }));
    },
    limit() {
      return +this.$route.query.limit || 10;
    },
  },
  methods: {
    // 2.获取所有的分类数据
    async fetchData() {
      return await getBlogCategories();
    },
    handouClick(item) {
      const query = {
        page: 1,
        limit: this.limit,
      };
      // 跳转到 当前的分类id 当前的页容量 newpage的页码
      if (item.id === -1) {
        // 表示当前没有分类
        this.$router.push({
          name: "Blog",
          query,
        });
      } else {
        this.$router.push({
          name: "CategoryBlog",
          query,
          params: {
            categoryId: item.id,
          },
        });
      }
    },
  },
  components: {
    RightList,
  },
};
</script>

<style lang="less" scoped>
.Category-cantainer {
  width: 300px;
  box-sizing: border-box;
  padding: 20px;
  h2 {
    font-weight: bold;
    letter-spacing: 2px;
    font-size: 1em;
    margin: 0;
  }
}
</style>